using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEditor;
using UnityEditor.UI;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace NGUI.Interactive
{
    public class NButton : Selectable
    {
        
        public string text
        {
            get => textGraphic.text;
            set { textGraphic.text = value; textGraphic.ForceMeshUpdate(); }
        }
        
        public TMP_Text textGraphic;
        public UnityEvent onClick;
        public AudioClip pointerEnterSound, pointerExitSound, pointerDownSound, pointerUpSound;

        private AudioSource AudioSource => GetComponent<AudioSource>();

        public override void OnPointerEnter(PointerEventData eventData)
        {
            base.OnPointerEnter(eventData);
            if (AudioSource)
                AudioSource.PlayOneShot(pointerEnterSound);
        }

        public override void OnPointerExit(PointerEventData eventData)
        {
            base.OnPointerExit(eventData);
            if (AudioSource)
                AudioSource.PlayOneShot(pointerExitSound);
        }

        public override void OnPointerDown(PointerEventData eventData)
        {
            base.OnPointerDown(eventData);
            if (AudioSource)
                AudioSource.PlayOneShot(pointerDownSound);
        }

        public override void OnPointerUp(PointerEventData eventData)
        {
            base.OnPointerUp(eventData);
            onClick.Invoke();
            if (AudioSource)
                AudioSource.PlayOneShot(pointerUpSound);
        }
        
        [Serializable]
        public class OnClickEvent : UnityEvent { }

        [CustomEditor(typeof(NButton))]
        private class EditorGUI : SelectableEditor
        {
            private SerializedProperty _onClick;
            private NButton Target => (NButton)target;

            protected override void OnEnable()
            {
                base.OnEnable();
                _onClick = serializedObject.FindProperty("onClick");
            }

            public override void OnInspectorGUI()
            {
                serializedObject.Update();
                
                base.OnInspectorGUI();
                
                Target.text = EditorGUILayout.TextField("Text", Target.text);
                EditorGUILayout.PropertyField(_onClick);

                serializedObject.ApplyModifiedProperties();
            }
        }
    }
}
